package com.lvxtech.gateway.service.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.lvxtech.gateway.service.RouteService;
@Service
public class RedisRouteServiceImpl implements RouteService{
	
	private static final Log log = LogFactory.getLog(RedisRouteServiceImpl.class);

	private static final String GATEWAY_ROUTES = "com:lvxtech:gateway_routes";

    @Autowired
    private RedisTemplate redisTemplate;

//    private Cache<String, RouteDefinition> gatewayRouteCache;

    private Map<String, RouteDefinition> routeDefinitionMaps = new HashMap<>();
    
    @PostConstruct
    public void loadRouteDefinition() {
        BoundHashOperations<String, String, RouteDefinition> bound = redisTemplate
                .boundHashOps(GATEWAY_ROUTES);
        Map<String, RouteDefinition> allRoutes = bound.entries();
        if(allRoutes==null||allRoutes.isEmpty()){
        	return;
        }
        routeDefinitionMaps.putAll(allRoutes);
        StringBuilder builder = new StringBuilder();
        builder.append("------------路由总计("+routeDefinitionMaps.size()+")------------");
        for (RouteDefinition val : routeDefinitionMaps.values()) {
        	builder.append("\n").append(JSON.toJSONString(val));
		}
        log.info(builder);
    }

    @Override
    public Collection<RouteDefinition> getRouteDefinitions() {
        return routeDefinitionMaps.values();
    }

    @Override
    public boolean save(RouteDefinition routeDefinition) {
//        routeDefinitionMaps.put(routeDefinition.getId(), routeDefinition);
    	BoundHashOperations<String, String, RouteDefinition> bound = redisTemplate
                .boundHashOps(GATEWAY_ROUTES);
    	bound.put(routeDefinition.getId(), routeDefinition);
        return true;
    }

    @Override
    public boolean delete(String routeId) {
//        routeDefinitionMaps.remove(routeId);
        return true;
    }
}
